package org.mogu.service;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


import org.mogu.db.ActiveUserHelper;
import org.mogu.staticvalue.Convert;
import org.mogu.task.UrlTask;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;


public class ImgSync {
	public ImgSync() {

	}

	// DefaultHttpClient client;
	// HttpResponse httpResponse;
	// HttpPost getResult=null;
	// HttpGet getMethod=null;

	// String uname;
	// String pwd;
	// String updateTime;

	// String nextdo;
	// String allcode;
	// String downloadcode = "";
	// boolean down = true;

	// ProgressDialog dialog;

	// List<NameValuePair> nameValuePair;

	SQLiteDatabase readdb = null;
	SQLiteDatabase wdb = null;
	// InfoService context=null;
	ActiveUserHelper auh = null;
	// boolean cdstatus=false;

	int num = 0;
	int numok = 0;

	private Map<String, String> urlMap = new HashMap<String, String>();

	public int sync(InfoService contex, ActiveUserHelper au, int i) {

		// this.context=contex;
		auh = au;

		int newcount = 0;
		try {
			synchronized (InfoSync.class) {
				readdb = auh.getReadableDatabase();
//				Cursor userCur = readdb
//						.rawQuery(
//								"select username from activeuser order by isactive desc",
//								null);
//
//				if (userCur.getCount() == 0) {
//					userCur.close();
//					return 0;
//				}
//				userCur.moveToFirst();
//				String uname = userCur.getString(0);
//				userCur.close();
				String[] w = { Convert.uname };
				boolean isImage=false;
				urlMap.clear();
				Cursor app = readdb.rawQuery(
						"select appid,url from app where username=?", w);
				app.moveToFirst();
				while (!app.isAfterLast()) {
					if (!urlMap.containsKey(app.getString(0))) {
						urlMap.put(app.getString(0), app.getString(1));
					}
					app.moveToNext();
				}
				app.close();
				Cursor activelist = readdb.rawQuery(
						"select id,code,type,isDown,appid from photo where isDown="
								+ String.valueOf(i)+" and username="+Convert.uname, null);

				if (activelist.getCount() > 0) {
					activelist.moveToFirst();
					DownloadPicTask dt;
					num = 0;
					isImage=true;
					while (!activelist.isAfterLast()) {
						
						dt = new DownloadPicTask();
						dt.imgid = activelist.getInt(0);
						dt.imgcode = activelist.getString(1);
						dt.fileType = activelist.getString(2);

						if (urlMap.containsKey(activelist.getString(4))) {
							dt.appUrl = urlMap.get(activelist.getString(4));
							dt.appid = activelist.getString(4);
						} else {
							continue;
						}
						dt.imgnum = i;
						dt.start();
						// ///
						num++;
						if (num > 10) {
							break;
						}
						activelist.moveToNext();
					}
				}
				activelist.close();
				
				activelist = readdb.rawQuery(
						"select id,code,type,isDown,appid from photoLib where isDown="
						+ String.valueOf(i)+" and username="+Convert.uname, null);
				String table="photoLib";
				if (activelist.getCount() > 0) {
					activelist.moveToFirst();
					DownloadPicTask dt;
					num = 0;
					isImage=true;
					while (!activelist.isAfterLast()) {
						
						dt = new DownloadPicTask();
						dt.table=table;
						dt.imgid = activelist.getInt(0);
						dt.imgcode = activelist.getString(1);
						dt.fileType = activelist.getString(2);
						
						if (urlMap.containsKey(activelist.getString(4))) {
							dt.appUrl = urlMap.get(activelist.getString(4));
							dt.appid = activelist.getString(4);
						} else {
							continue;
						}
						dt.imgnum = i;
						dt.start();
						// ///
						num++;
						if (num > 10) {
							break;
						}
						activelist.moveToNext();
					}
				}
				activelist.close();
				readdb.close();
				
				//设置是否还有图片等待下载
				Convert.hasImage=isImage;
			}

		} catch (Exception t) {
			Log.e("DB", "ImgSync-122");

		} finally {
			// readdb.close();
		}
		// auh.close();
		return newcount;

	}

	public static byte[] readStream(InputStream inStream) {
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			int offSet = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
				offSet = offSet + len;
			}
			outStream.close();
			inStream.close();
			return outStream.toByteArray();
		} catch (Exception e) {
			return null;
		}
	}

	// 保存文件
	public static void saveFile(String dir,String fileName,String type, byte[] buffer)
			throws IOException {

		File dirFile = new File(dir);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File saveFile = new File(dirFile, fileName+type);
			FileOutputStream outStream = new FileOutputStream(saveFile);
			outStream.write(buffer);
			outStream.close();
			File delFile=new File(dirFile,fileName+".jpg");
			if(delFile.exists()){
				delFile.delete();
			}
		}

	}

	public void saveJpg(Bitmap bm, String folder, String fileName)
			throws IOException {

		File dirFile = new File(folder);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		File myCaptureFile = new File(folder + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();

	}

	public class DownloadPicTask extends UrlTask {
		private Thread th;
		public String appUrl = "";
		public String picUrl = "/downLoad?image_id=";
		public int imgid;
		public String imgcode;
		public String appid = "";
		public String table = "photo";
		public int imgnum;
		public String fileType;
		public String folder = Convert.picPath;
		public String[] wheres;
		
		

		public DownloadPicTask() {
			// String[] ws={String.valueOf(imgid)};
			// wheres=ws;text/html
			th = new Thread() {
				public HttpURLConnection getConn(String url) {
					try{
						URL uri = new URL(url);
						HttpURLConnection conn = (HttpURLConnection) uri
								.openConnection();
						conn.setConnectTimeout(30 * 1000);
						conn.setRequestMethod("GET");
						return conn;
					}catch(Exception e){
						
					}
					return null;
				}
				
				public void run() {
					try {
						String picurl=setUrl();
						HttpURLConnection conn;
						String sql = "update "+table+" set isDown=";
						InputStream inStream;
						for(int i=0;i<2;i++){
							conn=getConn(picurl);
							
							
						
						if (conn.getResponseCode() == 200) {
							if(conn.getContentType().contains("text/html")){
								BufferedReader in = new BufferedReader(new InputStreamReader( 
					                    conn.getInputStream())); 
					            String line; 
					            picurl="";
					            while ((line = in.readLine()) != null) { 
					            	picurl += line; 
					            } 
					            in.close();
					            continue;
							}
							i++;
							inStream = conn.getInputStream();
							
							sql += 5;
							byte[] data = readStream(inStream);
							if (data != null) {
								
								if (conn.getContentType().contains("gif")) {
									saveFile(folder, imgcode + appid, ".gif", data);
								} else if (conn.getContentType().contains("jpeg")) {
									
									BitmapFactory.Options options = new BitmapFactory.Options(); 
									options.inJustDecodeBounds = true;
									Bitmap bmp = BitmapFactory.decodeByteArray(
											data, 0, data.length,options);// bitmap
									options.inJustDecodeBounds = false; 
							         //计算缩放比 
							         int be = (int)(options.outWidth / (float)Convert.picWidth); 
							         if (be <= 0) 
							              be = 1; 
							         options.inSampleSize = be;
							         bmp = BitmapFactory.decodeByteArray(
												data, 0, data.length,options);// bitmap
									saveJpg(bmp, folder, imgcode + appid
											+ ".jpg");
								}
							}
						} else {
							sql += imgnum + 1;
							i++;
						}
						sql += " where id=" + imgid;
						synchronized (InfoSync.class) {
							wdb = auh.getWritableDatabase();
							wdb.execSQL(sql);
							wdb.close();
						}
						}

					} catch (Exception e) {
						Log.e("DB",
								e.getMessage() == null ? "" : e.getMessage());
						Log.e("DB", "ImgSync-306");
					} finally {
						numok++;
						if (num == numok) {
							// wdb.close();
						}
					}

				}
			};
		}

		public void handleException() {

		}

		public void handleResult(String result) {

		}

		public String setUrl() {
			return this.appUrl + this.picUrl + this.imgcode;
		}

		public void start() {
			Log.e("img", setUrl());
			th.start();
		}
	}
}
